var express = require('express');
var router = express.Router();
let jwt  = require("jsonwebtoken");
let  leaveModel = require("../model/leave");

/* GET home page. */
router.get('/', function(req, res, next) {
    res.send("访问leave接口")
});

router.get("/student",(req,res,next)=>{
    let token  = req.headers.token;

    jwt.verify(token,"abc",async (err,info)=>{//解析token

        if(!err){
            let  type = info.type;
            if(type==2){//查询学生
                let  userid  = info._id;
                let  list = await  leaveModel.query({userid});

                res.json({
                    code:1,
                    msg:"查询完成",
                    list
                })
            }else{
                res.json({
                    code:0,
                    msg:"权限不够"
                })
            }

        }else{
            res.json({
                code:0,
                msg:"token解析异常"
            })
        }
    })





})

router.post("/add",(req,res,next)=>{

    let {reason,start,end ,extend,usertype=1} = req.body;

    //但是数据库里面要有userid  username
    let  token  = req.headers.token;

    //解析token

    jwt.verify(token,"abc",async (err,info)=>{
            // res.json({err,info});
            if(err){
                res.json({
                    code:0,
                    msg:"token 异常请重新登录"
                })
            }else{
                let  type = info.type;//info是用户信息  type 是用户类别

                if(type ==2){
                    //对了  就可以把数据写入数据库
                    let  userid = info._id;
                    let  username = info.username;

                    let  result  = await  leaveModel.add({
                        userid,username,reason,start,end,extend,"type":usertype

                    })


                    res.json({
                        code:1,
                        msg:"新增成功",
                        data:result[0]
                    })



                

                }else{
                    res.json({
                        code:0,
                        msg:"权限不够 请重新登录"
                    })
                }





            }

    })





    // res.json({
    //     reason,start,end,token

    // })



})

module.exports = router;
